﻿using System;
using System.Drawing;
using System.IO;
using System.Text;
using Emgu.CV;
using Emgu.CV.Structure;

namespace AsmDotNet
{
  public  class ASM
  {
      private readonly asmLibraryDotNet.Class1 _asm;
        /// <param name="model">File model (default my68-1d.amf)</param>
        public ASM(string model = null)
        {
            if (model == null) model = Properties.Settings.Default.Model;
            unsafe
            {
                byte[] bytes = Encoding.ASCII.GetBytes(model);
                sbyte* sp;
                fixed (byte* p = bytes)
                    sp = (sbyte*)p;
                _asm = new asmLibraryDotNet.Class1(sp);
            }
        }

        /// <summary>
        /// Find points
        /// </summary>
        public FlandMark Find(Image<Gray, byte> image, int iteration = 20)
        {
            string f = Guid.NewGuid().ToString();
            string s;
            image.Save(f + ".bmp");
            unsafe
            {
                sbyte* inf;
                fixed (byte* p = Encoding.ASCII.GetBytes(f + ".bmp"))
                    inf = (sbyte*)p;
                s = _asm.Detect(inf, iteration);
            }
            var r = new FlandMark(s);
            File.Delete(f + ".bmp");
            return r;
        }

        /// <summary>
        /// Find points
        /// </summary>
        public FlandMark Find(Image<Bgr, byte> image, int iteration = 20)
        {
            var i = image.Convert<Gray, byte>();
            var r = Find(i, iteration);
            i.Dispose();
            return r;
        }

        /// <summary>
        /// Find points
        /// </summary>
        public FlandMark Find(Bitmap image, int iteration = 20)
        {
            var i = new Image<Gray, byte>(image);
            var r = Find(i, iteration);
            i.Dispose();
            return r;
        }

    }
}
